package com.cn.zengzeng.spbzengzeng.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.zengzeng.spbzengzeng.po.UserPo;
import com.cn.zengzeng.spbzengzeng.vo.ActionResult;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author: ZhangZengZeng
 * @Date: 2023/3/31 17:00
 */
@Slf4j
@Service
public class AccountService {
    @Resource
    private Cache<String,Object> cache ;
    @Resource
    private UserAccountService userAccountService ;
    @Resource
    private RabbitTemplate rabbitTemplate ;
    @Nullable
    public ActionResult getRegisterAction (UserPo userPo) {
        String account = userPo.getAccount();
        String o = (String) cache.asMap().get(account);
        if(o!=null){
            log.info("getRegisterAction查询缓存:{}",o);
            return ActionResult.getSuccessResult("5005");
        }
        UserPo usp = userAccountService.selectAccount(account);
        log.info("getRegisterAction查询响应:{}",usp);
        if(usp!=null){
            //注册防止重复请求缓存
            cache.put(account,account);
            return ActionResult.getSuccessResult("5005");
        }
        //检测邮箱是否绑定其他账号
        boolean b = userAccountService.checkEmailUse(userPo.getEmail());
        if(b){
            return ActionResult.getSuccessResult("5012");
        }
        int register = userAccountService.register(userPo);
        log.info("getRegisterAction注册响应:{}",register);
        if(register>0){
            rabbitTemplate.convertAndSend("loginEmail",JSON.toJSONString(userPo));
            //注册缓存该账号激活凭证
            cache.put("ACTIVE"+account,account);
            return ActionResult.getSuccessResult("200",null);
        }
        return null;
    }

    public void extracted (String email,String verificationCode) {
        JSONObject topicData = new JSONObject();
        topicData.put("email",email);
        topicData.put("verificationCode",verificationCode);
        cache.put(email+","+verificationCode,verificationCode);
        rabbitTemplate.convertAndSend("forgetPassEmail_topic",topicData.toJSONString());
    }
    @Async("asyncExecutor")
    public void test3()  {
        log.info("asyncExecutor自定义线程池异步执行");
    }
}
